package com.xiaol.business.controller;

import com.xiaol.business.form.StudentForm;
import com.xiaol.business.model.Student;
import com.xiaol.framework.result.ResultUtil;
import com.xiaol.framework.result.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

@RestController
@RequestMapping(value="/form")
public class FormController {

    /**
     * 表单验证：
     *      1.不单独一个一个的接收字段了，把字段整个放入一个bean中
     *      2.在bean里配置
     *      3.加注解@Valid进行验证，如果不加这个注解，不会进行验证
     *      4.入参里加入BindingResult，用于存放验证结果
     *          判断是否有错误 bindingResult.hasErrors()
     *          获取出错的字段 bindingResult.getFieldError().getDefaultMessage()
     * @param studentForm
     * @return
     */
    @RequestMapping(value = "/valid", method = RequestMethod.GET)
    public Result<Student> validStudent(@Valid StudentForm studentForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            return ResultUtil.error(1001, msg);
        }
        Student student = new Student();
        BeanUtils.copyProperties(studentForm,student);
        return ResultUtil.success(student);
    }

    /**
     * 格式化JSON：
     *      1.spring-boot默认的jsaon解析器是jackson
     *      2.格式化jason的时候在bean里直接配就可以了
     * @return
     */
    @RequestMapping(value = "/json", method = RequestMethod.GET)
    public StudentForm jsonTest(){
        StudentForm studentForm = new StudentForm();
        studentForm.setName("JSONTEST");
        studentForm.setAge(12);
        studentForm.setAccessTime(new Date());
        return studentForm;
    }
}
